<?php

class lb_db_operation {

	/**
	*Open a connection to a DB Server
	*
	* @author	Armin Borumand
	* @param	string	db host
	* @param	string	db name
	* @param	string	db username
	* @param	string	db password
	* @return	resource	db link identifier
	*/		
	function db_connect ($host=false, $db=false, $user=false, $pass=false){
		global $lb;
		
		if($host === false){
			$host = $lb['db_host'];
			$user = $lb['db_user'];
			$pass = $lb['db_pass'];
			$db = $lb['db_name'];
		}
		
		$db_id = mysql_connect ($host, $user, $pass);
		
		if(!mysql_select_db ($db, $db_id)){
			return false;
		}
		
		return $db_id;
	}	
	
	/**
	*Escapes a string for use in a db_query
	*
	* @author	Armin Borumand
	* @param	string	query string string
	* @return	string	a safe string for use in a db_query
	*/		
	function db_escape_string ($str, $binary=false){
		return mysql_escape_string ($str);
	}
	
	/**
	*Send a DB query
	*
	* @author	Armin Borumand
	* @param	string	query
	* @param	resource	db link id
	* @return	resource	resource identifier
	*/	
	function db_query ($query, $db=NULL){
		if($db == NULL){
			$db = $this->db;
		}
		return mysql_query ($query, $db);
	}
	
	/**
	*Get the ID generated from the previous INSERT operation
	*
	* @author	Armin Borumand
	* @param	resource	db link id
	* @return	int		the ID generated from the previous INSERT operation
	*/
	function db_insert_id ($db=NULL){
		if($db == NULL){
			$db = $this->db;
		}
		return @mysql_insert_id ($db);
	}
	
	/**
	*Get number of affected rows in previous DB operation
	*
	* @author	Armin Borumand
	* @return	int		 the number of affected rows in previous DB operation
	*/	
	function db_affected_rows (){
		return @mysql_affected_rows ($this->db);
	}
	
	/**
	*Fetch a result row as an associative array
	*
	* @author	Armin Borumand
	* @param	resource	the query result
	* @return	int		 an associative array that corresponds to the fetched row, or FALSE if there are no more rows
	*/	
	function db_fetch_assoc ($result){
		return @mysql_fetch_assoc ($result);
	}
	
	/**
	*Get number of rows in result
	*
	* @author	Armin Borumand
	* @param	resource	the query result
	* @return	int		 the number of rows in a result set
	*/
	function db_num_rows ($result){
		return @mysql_num_rows ($result);
	}
	
	/**
	 * Convert db timestamp to Unix timestamp
	 *
	 * @author	Armin borumand
	 * @param	string	db timestamp
	 * @retuen	integer	timestamp
	 */
	function timestamp($db_timestamp){
		$db_timestamp = explode(' ', $db_timestamp);
		
		$date = explode('-', $db_timestamp[0]);
		$time = explode(':', $db_timestamp[1]);
		
		return mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
	}
}
